// pages/user/autho.js
//获取应用实例
const app = getApp()
const userId = wx.getStorageSync(app.config.userId)

Page({
  data: {
    motto: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },
  onLoad: function() {
    // if (userId != ""){
    //   wx.redirectTo({
    //     url: '/pages/login/login'
    //   })
    //   return
    // }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    app.tip.showLoading()
    console.log(e)
    var userInfo = app.globalData.userInfo = e.detail.userInfo
    if (userInfo == undefined) {
      app.tip.toast("授权失败")

      app.tip.hideLoading()
      return
    }
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    //req jscode
    // this.login(e)
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  // 登录
  login: function(e) {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        app.requestAPI.wxLogin(res.code)
          .then(d => {
            app.tip.log(d)
            if (d.code == 200) {
              // this.saveUserInfo(d.data)
              app.saveUserInfo(d.data)

              wx.setStorageSync(app.config.encryptedData, e.detail.encryptedData)
              wx.setStorageSync(app.config.iv, e.detail.iv)

              var userId = wx.getStorageSync(app.config.userId)
              var sessionKey = wx.getStorageSync(app.config.sessionKey)
              var encryptedData = wx.getStorageSync(app.config.encryptedData)
              var iv = wx.getStorageSync(app.config.iv)

              this.decryptUserInfo(userId, sessionKey, encryptedData, iv)
            } else {
              app.tip.toast(d.msg)
              app.tip.hideLoading()
            }
          }).catch(e => {
            app.tip.toast('网络异常')
            app.tip.log('wxLogin请求异常')
            app.tip.hideLoading()
          });
      }
    })
  },
  /**
    * 用户信息补全
    */
  decryptUserInfo: function (userId, sessionKey, encryptedData, iv) {
    app.requestAPI.decryptUserInfo(userId, sessionKey, encryptedData, iv)
      .then(d => {
        app.tip.log(d)
        if (d.code == 200) {
          app.saveUserInfo(d.data)
          wx.redirectTo({
            url: '/pages/login/login',
          })
          app.tip.toast("授权成功")
          // that.setData({
          //   avatarUrl: d.data.avatarUrl,
          //   nickName: d.data.nickName
          // })
        } else {
          app.tip.toast(d.msg)
          app.tip.hideLoading()
        }
      }).catch(e => {
        app.tip.toast('网络异常')
        app.tip.log('decryptUserInfo请求异常')
        app.tip.hideLoading()
      });
  },


})